//
//  MineViewController.m
//  LoveCar
//
//  Created by Du Bin on 15/5/27.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "MineViewController.h"
#import "DetViewController.h"
#import "DetailsCell.h"
#import "aboutLoveCarViewViewController.h"
#import "UMSocial.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface MineViewController () <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate>

@property (nonatomic, retain) NSArray *files;
@property (nonatomic, retain) UITableView *logTable;
@property (nonatomic, retain) UIImageView *logView;

@end

@implementation MineViewController

- (void)dealloc
{
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    self.navigationItem.title = @"我の爱车";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self createTableView];
    [self topLabel];
    [self.logTable reloadData];

    
}

- (void)topLabel
{
    UIImageView *topImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    [topImage setImage:[UIImage imageNamed:@"backImage.jpg"]];
    [topImage setBackgroundColor:[UIColor lightGrayColor]];
    [self.view addSubview:topImage];
    [topImage release];
    
    self.logView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logIn.jpg"]];
    _logView.frame = CGRectMake(self.view.frame.size.width / 2 - 50, 50, 100, 100);
    _logView.layer.masksToBounds = YES;
    _logView.layer.cornerRadius = 50;
    [_logView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAciton:)];
    [_logView addGestureRecognizer:tap];
    [self.view addSubview:_logView];
    [_logView release];
    [tap release];
}

- (void)tapAciton:(id)sender
{
    BOOL isOauth = [UMSocialAccountManager isOauthWithPlatform:UMShareToSina];
    
    if(isOauth == YES){
        NSLog(@"取消登录");
        UIActionSheet *unOauthActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"解除授权", nil];
        unOauthActionSheet.destructiveButtonIndex = 0;
//        unOauthActionSheet.tag = switcher.tag;
        [unOauthActionSheet showInView:self.tabBarController.tabBar];
        
    } if (isOauth == NO) {
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        
        snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
            
            //          获取微博用户名、uid、token等
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                //            UMSocialResponseEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
                //            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
            }});
        
        //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
        [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
            NSLog(@"SnsInformation is %@",response.data);
            [self.logView sd_setImageWithURL:[NSURL URLWithString:[response.data objectForKey:@"profile_image_url"]]];
            NSLog(@"imageUrl = %@", [response.data objectForKey:@"profile_image_url"]);
        }];
    }
}

#pragma UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

    [[UMSocialDataService defaultDataService] requestUnOauthWithType:UMShareToSina  completion:^(UMSocialResponseEntity *response){
        NSLog(@"response is %@",response);
    }];
}

- (void)createTableView
{
    self.logTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 180, self.view.frame.size.width, self.view.frame.size.height - 64 - 29 - 200) style:UITableViewStyleGrouped];
    self.logTable.delegate = self;
    self.logTable.dataSource = self;
    [self.view addSubview:self.logTable];
    [self.logTable release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0||section == 3) {
        return 4;
    } if (section == 0||section == 2) {
        return 2;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString *cellName = @"cell";
    DetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[DetailsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (section) {
            case 0:
                if(row == 0)
                {
                    cell.detLabel.text =  @"爱论坛";
                    [cell.detView setImage:[UIImage imageNamed:@"det.png"]];
                } if(row == 1)
                {
                    cell.detLabel.text =  @"爱商城";
                    [cell.detView setImage:[UIImage imageNamed:@"det.png"]];
                } if(row == 2)
                {
                    cell.detLabel.text =  @"爱美车";
                    [cell.detView setImage:[UIImage imageNamed:@"det.png"]];
                } if(row == 3)
                {
                    cell.detLabel.text =  @"爱车惠";
                    [cell.detView setImage:[UIImage imageNamed:@"det.png"]];
                }
                break;
            case 1:
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                ^{
                    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                    self.files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                    NSLog(@"files :%lu",[self.files count]);
                ;});
                cell.detLabel.text =  @"清除缓存";
                [cell.detView setImage:[UIImage imageNamed:@"clear.png"]];
                break;
            case 2:
                if(row == 0)
                {
                    cell.detLabel.text =  @"关于爱评车";
                    [cell.detView setImage:[UIImage imageNamed:@"about.png"]];
                } if(row == 1){
                    cell.detLabel.text =  @"评分";
                    [cell.detView setImage:[UIImage imageNamed:@"good.png"]];
                }
                break;
            default:
            break;
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        NSLog(@"1 - 1 爱论坛");
        DetViewController *det = [[DetViewController alloc] init];
        det.str = @"http://baa.m.yiche.com";
        [self.navigationController pushViewController:det animated:YES];

    } if (indexPath.section == 0 && indexPath.row == 1) {
        
        NSLog(@"1 - 2 爱商城");
        DetViewController *det = [[DetViewController alloc] init];
        det.str = @"http://m.yichemall.com/?source=ycapp-tool-1";
        [self.navigationController pushViewController:det animated:YES];
        
    } if (indexPath.section == 0 && indexPath.row == 2) {
        
        NSLog(@"1 - 3 爱美车");
        DetViewController *det = [[DetViewController alloc] init];
        det.str = @"http://yanghu.m.yiche.com/?source=yctool";
        [self.navigationController pushViewController:det animated:YES];
        
    } if (indexPath.section == 0 && indexPath.row == 3) {
        
        NSLog(@"1 - 4 爱车惠");
        DetViewController *det = [[DetViewController alloc] init];
        det.str = @"http://m.huimaiche.com/?tracker_u=215_ycappty";
        [self.navigationController pushViewController:det animated:YES];
        
    } if (indexPath.section == 1 &&indexPath.row == 0) {
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"everLaunched"];
        NSLog(@"2 - 1 清除缓存");
        
#pragma - 清除缓存 - 
        
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{ NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
                       
                       self.files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       
                       for (NSString *p in self.files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
//                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
                   });
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"清理完成" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
        [alert show];
        [alert release];

    } if (indexPath.section == 2 && indexPath.row == 0) {
        NSLog(@"3 - 2 关于我们");
        
        aboutLoveCarViewViewController *about = [[aboutLoveCarViewViewController alloc] init];
        [self.navigationController pushViewController:about animated:YES];
        [about release];
        
        
    } if (indexPath.section == 2 && indexPath.row == 1) {
        NSLog(@"3 - 2 评分");
        
        NSString *str = [NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=xxxxxx" ];
        if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)){
            str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/idxxxxxxx"];
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
    }
}

//-(void)clearCacheSuccess
//{
//    NSLog(@"清理成功 %ld", [self.files count]);
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
